import React from 'react'
import {Form, Row, Col, Modal, Input, Select, Tree, Button, Upload, Icon} from 'antd';
import API from "../../../axios/api";
import {beforeUpload, checkUploadFiles} from '../../../utils/utils'
import './form.less'
import config from '../../../config';
const BaseUrl = config.apiURL

const { TextArea } = Input;

let id = 0

// @Form.create()
class ArticleForm extends React.Component {
    constructor(props){
        super(props)
        this.state = {  
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
            treeData: [],
            editorContent: '',
            imgList: [],
            logImage:[],
            // fileList: [],
            clear: false,
            previewVisible: false,
            previewImage: '',
            fileList: [
                {
                    uid: '-1',
                    name: 'xxx.png',
                    status: 'done',
                    url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                },
            ],
            Id: "",
            shareImage: [],
            detailList: [{}]
        };
        this.ArticleLabelList = []
    }

    // 获取文章标签列表
    initArticleLabelList =  async () => {
        await API.fetchArticleLabelList().then((res) => {
            if(res.Code === 200) {
                this.ArticleLabelList =  res.Data
            }
        })
    }

    onExpand = expandedKeys => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };

    onCheck = checkedKeys => {
        this.setState({ checkedKeys });
    };

    onSelect = (selectedKeys, info) => {
        this.setState({ selectedKeys });
    }

    componentWillMount() {
        const { form, data } = this.props;
        if(data){
            form.setFieldsValue({
                keys: data.keys,
                details: data.details
            });
        }
    }

    componentDidMount() {
       this.initArticleLabelList()
    }

    handleSubmit = e => {
        e && e.preventDefault()     

        this.props.form.validateFields((err, values) => {
            if (!err) {
                const { keys, details } = values;
                values.ArticleType = 1
                values.TemplateId = ''
                values.ArticleDescribe = ''
                values.ArticleContentList = []
                values.ArticleLogo = values.ArticleLogo && values.ArticleLogo.length > 0 ? values.ArticleLogo[0].response.Data: ''
                values.ArticleShareImage = values.ArticleShareImage && values.ArticleShareImage.length > 0 ? values.ArticleShareImage[0].response.Data: ''
                values.ArticleCategoryId = values.Type
                if(details){
                    // ContentType = 内容1 ， 图片2， 视频3
                    details.map(item => {
                        if(item.file){
                            item.file.map(f => {
                                let _item = {
                                    Content: f.response.Data ,
                                    ContentType: f.type.includes('image') ? 2 : (f.type.includes('video')? 3: 1)
                                }
                                values.ArticleContentList.push(_item)
                            })
                        }
                        if(item.Content)
                        {
                            values.ArticleContentList.push({
                                ContentType: 1,
                                Content: item.Content
                            })
                        }
                    })
                }
                values.keys = null
                values.details = null
                const { onOk } = this.props
                onOk && onOk(values)
                this.props.form.resetFields()
                this.setState({
                 logImage : [],
                  shareImage: []
                })
            }
        })
    }

    handlerClose = (fn) => {
        this.props.form.resetFields()
        this.setState({ checkedKeys : []})
        fn()
    }

    getRolePermByRoleId =  async (Id) => {
        const parms = {
            Id
        }
        await API.getRolePermissionByRoleId(parms).then((res) => {
            if(res.Code === 200) {
                let checkedKeys = res.Data
                this.setState({
                    checkedKeys
                });
            }
        })
    }


    onBlurEditor = (value) =>{
        this.setState({
            editorContent: value
        })
    }

    onImgUploadChange = (value) =>{
        this.setState({
            imgList : value
        })
    }

    componentWillReceiveProps(nextProps, nextContext) {
        if(nextProps.data){
            id = nextProps.data.keys ? nextProps.data.keys.length : 0
        }
    }

    shareNormFile = e => {
        if (Array.isArray(e)) {
            return e;
        }
        this.setState({
            shareImage: e.fileList
        })
        return e && e.fileList;
    }

    logNormFile= e => {
        if (Array.isArray(e)) {
            return e;
        }
        this.setState({
            logImage: e.fileList
        })
        return e && e.fileList;
    }

    normFile = e => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }

    addItem = (type) => {
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        const details = form.getFieldValue('details');
        // const nextKeys = keys.concat(id++);
        const nextKeys = keys.concat({id: id++, type: type});
        // can use data-binding to set
        // important! notify form to detect changes
        form.setFieldsValue({
            keys: nextKeys,
        });
    }

    remove = k => {
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        // We need at least one passenger
        if (keys.length === 1) {
            return;
        }

        // can use data-binding to set
        form.setFieldsValue({
            keys: keys.filter(key => key !== k),
        });
    };

    onRomoveImg = (data) =>{
        const { form } = this.props;
        const keys = form.getFieldValue('keys');
        const details = form.getFieldValue('details');
        form.setFieldsValue({
            details: data,
        });
    }

    render(){
        const {
            modalKey,
            visible,
            title,
            fields,
            onCancel,
            onOk,
            okText,
            width,
            data,
            CategoryList
        } = this.props
        console.log(data)
        let item =  data.ArticleContentList
        let formItems = item && item.length > 0 && item.map((item,index) => (
          <div>
                {
                  item.ContentType == 1 ? 
                        <div className="infoView" dangerouslySetInnerHTML={{__html: item.Content}}></div>:
                  item.ContentType == 2 ? 
                  <img className="content-img" src={item.Content} />:
                  item.ContentType == 3 ? 
                  <video className="content-img" src={item.Content} controls="controls"> </video>:''
                
                }
          </div>
        ))


        return (
            <Modal
                wrapClassName="form"
                key={modalKey}
                visible={visible}
                title={title}
                onCancel={onCancel}
                footer={null}
                width={width}
                maskClosable={true}
            >   
                <div className="bgbox">
                    <div className="content">
                        <div className="title">
                            {data.Title}
                        </div>
                          {formItems}
                    </div>
                </div>
            </Modal>
        )
    }
}
let ArticleModalForm = Form.create()(ArticleForm)
export default ArticleModalForm

